package com.icez.base_util_library

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.util.*

/**
 *  文件压缩工具类
 */
class CompressUtil {
    companion object {
        val instance: CompressUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            CompressUtil()
        }
    }


    /**
     *  压缩图片,压缩业务处理后，记得delete；不然会出现二张图片,占用手机磁盘
     * @param quality 压缩的质量 压缩率
     * Bitmap.CompressFormat.PNG -> 压缩png
     * Bitmap.CompressFormat.WEBP_LOSSLESS -> 压缩webp //无损压缩 质量 0-》快速压缩,但是文件大   100 -》压缩慢且耗时,但是文件小
     * Bitmap.CompressFormat.WEBP_LOSSY -> 压缩webp //有损压缩 质量 0-》压缩最小尺寸  100 -》压缩最大尺寸
     * Bitmap.CompressFormat.JPEG -> 压缩jpeg
     */
    public suspend fun compressImageForWebp(
        context: Context,
        imgFilePath: String?,
        quality: Int
    ): File? {
        val dirPath = context.cacheDir.absolutePath+File.separator+Environment.DIRECTORY_PICTURES
        val fileName = "bitmap_" + imgFilePath?.substringAfterLast("/")?.substringBeforeLast(".")+".webp"
        var mQuality = 0
        if (quality <= 0) {
            return null
        } else if (quality >= 100) {
            return null
        } else {
            mQuality = 100 - quality
        }
        val dirFile = File(dirPath)
        if (!dirFile.exists()) {
            dirFile.mkdirs()
        }
        val file = File(dirFile, fileName)
        if (!file.exists()) {
            file.createNewFile()
        }
        val mFileOutputStream = FileOutputStream(file)
        val bitmap = BitmapFactory.decodeFile(imgFilePath) ?: return null
        bitmap.run {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                this.compress(Bitmap.CompressFormat.WEBP_LOSSLESS, quality, mFileOutputStream)
            } else {
                this.compress(Bitmap.CompressFormat.WEBP, mQuality, mFileOutputStream)
            }
        }
        return file
    }


}